package com.smart.third.dao;

import com.smart.third.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 用户dao层
 *
 * @author junrui.wang
 * @create 2018/3/8
 */
@Repository //通过spring注解定义一个Dao
public class UserDao {
    private JdbcTemplate jdbcTemplate;

    private final static String MATCH_COUNT_SQL = "SELECT count(*) AS m_c FROM t_user WHERE user_name=? AND password=?";

    private final static String MATCH_USER_SQL = "SELECT * FROM t_user WHERE user_name=?";

    private final static String UPDATE_LOGIN_SQL = "UPDATE t_user SET last_visit=?,last_ip=?,credits=? WHERE user_id=?";

    @Autowired //自动注入JdbcTemplate的Bean
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int getMatchCount(String userName, String password){
        List<Map<String, Object>> datas = jdbcTemplate.queryForList(MATCH_COUNT_SQL, userName, password);
        Map<String, Object> data = datas.get(0);
        return Integer.valueOf(data.get("m_c").toString());
    }

    public User findUserByUserName(final String userName){
        final User user = new User();
        jdbcTemplate.query(MATCH_USER_SQL, new Object[]{userName},
                //匿名类方法实现的回调函数
                new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getInt("user_id"));
                        user.setUserName(userName);
                        user.setCredits(rs.getInt("credits"));
                    }
        });

        return user;
    }

    public int updateLoginInfo(User user){
        return jdbcTemplate.update(UPDATE_LOGIN_SQL, new Object[] {(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getLastVisit())),
                user.getLastIp(), user.getCredits(), user.getUserId()});
    }
}
